<?php

namespace app\controller\crm;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Filesystem;
use think\exception\ValidateException;

class Order extends BaseController
{
    /**
     * 获取业务订单列表
     */
    public function list()
    {
        $params = Request::param();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 20;
        $customerId = $params['customer_id'] ?? 0;
        $orderType = $params['order_type'] ?? '';
        $status = $params['status'] ?? '';

        $query = Db::name('crm_order')
            ->alias('o')
            ->field('o.*, c.name as customer_name, u.name as user_name, d.title as dept_name')
            ->leftJoin('crm_customer c', 'o.customer_id = c.id')
            ->leftJoin('admin u', 'o.signer_id = u.id')
            ->leftJoin('department d', 'u.did = d.id')
            ->whereExp('o.delete_time', 'IS NULL OR o.delete_time = 0'); // 修复：匹配NULL或0

        if ($customerId) {
            $query->where('o.customer_id', $customerId);
        }

        if ($orderType !== '') {
            $query->where('o.order_type', $orderType);
        }

        if ($status !== '') {
            $query->where('o.status', $status);
        }

        // 数据权限控制
        $userId = $this->getUserId();
        if ($userId > 0) {
            // 获取当前用户信息
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();

            if ($userInfo) {
                if ($userInfo['group_id'] == 1) {
                    // 超级管理员：可以查看所有订单，不限制
                } elseif ($userInfo['group_id'] == 2) {
                    // 部门经理：只能查看本部门的订单
                    $query->where('u.did', $userInfo['did']);
                } elseif ($userInfo['group_id'] > 2) {
                    // 销售人员：只能查看自己创建的订单
                    $query->where('o.signer_id', $userId);
                }
            }
        }

        $total = $query->count();
        $list = $query->order('o.create_time', 'desc')
            ->page($page, $limit)
            ->select();

        return $this->paginate($list ? $list->toArray() : [], $total, (int)$page, (int)$limit);
    }
    
    /**
     * 添加业务订单
     */
    public function add()
    {
        $params = Request::param();
        $files = Request::file();
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        // 检查客户是否存在
        $customer = Db::name('crm_customer')
            ->where('id', $params['customer_id'])
            ->where('delete_time', null)
            ->find();
            
        if (!$customer) {
            return $this->error('客户不存在');
        }
        
        // 检查权限
        if ($customer['user_id'] != $userId) {
            // 获取用户信息判断权限
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();
            
            if (!$userInfo || (isset($userInfo['group_id']) && $userInfo['group_id'] > 2)) {
                return $this->error('无权限为该客户创建订单');
            }
        }
        
        $data = [
            'order_no' => $this->generateOrderNo(),
            'customer_id' => $params['customer_id'],
            'order_type' => $params['order_type'],
            'title' => $params['title'],
            'amount' => $params['amount'] ?? 0,
            'description' => $params['description'] ?? '',
            'contract_no' => $params['contract_no'] ?? '',
            'payment_type' => $params['payment_type'] ?? 1,
            'payment_plan' => $params['payment_plan'] ?? '',
            'status' => 1, // 待审核
            'signer_id' => $userId,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s')
        ];
        
        // 处理合同文件上传
        if (isset($files['contract_files'])) {
            $contractFiles = $this->uploadContractFiles($files['contract_files']);
            if ($contractFiles['code'] != 0) {
                return $this->error($contractFiles['msg']);
            }
            $data['contract_files'] = json_encode($contractFiles['data'], JSON_UNESCAPED_UNICODE);
        }
        
        $id = Db::name('crm_order')->insertGetId($data);
        
        if ($id) {
            return $this->success(['id' => $id], '订单创建成功，等待审核');
        }
        
        return $this->error('订单创建失败');
    }
    
    /**
     * 编辑业务订单
     */
    public function edit()
    {
        $params = Request::param();
        $files = Request::file();
        $id = $params['id'];
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        $order = Db::name('crm_order')->where('id', $id)->find();
        if (!$order) {
            return $this->error('订单不存在');
        }
        
        // 检查权限
        if ($order['signer_id'] != $userId) {
            // 获取用户信息判断权限
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();
            
            if (!$userInfo || (isset($userInfo['group_id']) && $userInfo['group_id'] > 2)) {
                return $this->error('无权限编辑');
            }
        }
        
        // 只有待审核状态的订单可以编辑
        if ($order['status'] != 1) {
            return $this->error('只有待审核状态的订单可以编辑');
        }
        
        $data = [
            'title' => $params['title'] ?? $order['title'],
            'amount' => $params['amount'] ?? $order['amount'],
            'description' => $params['description'] ?? $order['description'],
            'contract_no' => $params['contract_no'] ?? $order['contract_no'],
            'payment_type' => $params['payment_type'] ?? $order['payment_type'],
            'payment_plan' => $params['payment_plan'] ?? $order['payment_plan'],
            'update_time' => date('Y-m-d H:i:s')
        ];
        
        // 处理合同文件上传
        if (isset($files['contract_files'])) {
            $contractFiles = $this->uploadContractFiles($files['contract_files']);
            if ($contractFiles['code'] != 0) {
                return $this->error($contractFiles['msg']);
            }
            $data['contract_files'] = json_encode($contractFiles['data'], JSON_UNESCAPED_UNICODE);
        } elseif (isset($params['contract_files'])) {
            // 如果有合同文件数据但没有新文件上传，使用现有数据
            $data['contract_files'] = $params['contract_files'];
        }
        
        $result = Db::name('crm_order')->where('id', $id)->update($data);
        
        if ($result) {
            return $this->success('更新成功');
        }
        
        return $this->error('更新失败');
    }
    
    /**
     * 删除业务订单
     */
    public function del()
    {
        $params = Request::param();
        $id = $params['id'];
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        $order = Db::name('crm_order')->where('id', $id)->find();
        if (!$order) {
            return $this->error('订单不存在');
        }
        
        // 检查权限
        if ($order['signer_id'] != $userId) {
            // 获取用户信息判断权限
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();
            
            if (!$userInfo || (isset($userInfo['group_id']) && $userInfo['group_id'] > 2)) {
                return $this->error('无权限删除');
            }
        }
        
        // 只有待审核状态的订单可以删除
        if ($order['status'] != 1) {
            return $this->error('只有待审核状态的订单可以删除');
        }
        
        $result = Db::name('crm_order')
            ->where('id', $id)
            ->update(['delete_time' => date('Y-m-d H:i:s')]);
            
        if ($result) {
            return $this->success('删除成功');
        }
        
        return $this->error('删除失败');
    }
    
    /**
     * 审核业务订单
     */
    public function review()
    {
        $params = Request::param();
        $id = $params['id'];
        $reviewType = $params['review_type']; // 1: 到账审核, 2: 合同回收审核
        $status = $params['status']; // 2: 通过, 3: 驳回
        $reviewComment = $params['review_comment'] ?? '';
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        // 获取用户信息判断是否为管理员
        $userInfo = Db::name('admin')
            ->field('id, group_id, did')
            ->where('id', $userId)
            ->find();
        
        // 只有管理员可以审核
        if (!$userInfo || (isset($userInfo['group_id']) && $userInfo['group_id'] != 1)) {
            return $this->error('无权限审核');
        }
        
        $order = Db::name('crm_order')->where('id', $id)->find();
        if (!$order) {
            return $this->error('订单不存在');
        }
        
        // 检查审核状态
        if ($reviewType == 1 && $order['payment_status'] != 1) {
            return $this->error('订单不处于待到账审核状态');
        }
        
        if ($reviewType == 2 && $order['contract_status'] != 1) {
            return $this->error('订单不处于待合同回收审核状态');
        }
        
        // 创建审核记录
        $reviewData = [
            'order_id' => $id,
            'review_type' => $reviewType,
            'reviewer_id' => $userId,
            'review_status' => $status,
            'review_comment' => $reviewComment,
            'create_time' => date('Y-m-d H:i:s')
        ];
        
        Db::name('crm_order_review')->insert($reviewData);
        
        // 更新订单状态
        $updateData = ['update_time' => date('Y-m-d H:i:s')];
        
        if ($reviewType == 1) {
            $updateData['payment_status'] = $status;
            if ($status == 2) {
                $updateData['payment_time'] = date('Y-m-d H:i:s');
            }
        } elseif ($reviewType == 2) {
            $updateData['contract_status'] = $status;
            if ($status == 2) {
                $updateData['contract_receive_time'] = date('Y-m-d H:i:s');
                // 合同回收审核通过后，标记客户为已合作
                Db::name('crm_customer')
                    ->where('id', $order['customer_id'])
                    ->update([
                        'is_cooperation' => 1,
                        'cooperation_time' => date('Y-m-d H:i:s')
                    ]);
            }
        }
        
        // 如果两个审核都通过，订单状态变为已完成
        if ($order['payment_status'] == 2 && $status == 2 && $reviewType == 2) {
            $updateData['status'] = 4; // 已完成
        } elseif ($order['contract_status'] == 2 && $status == 2 && $reviewType == 1) {
            $updateData['status'] = 4; // 已完成
        }
        
        $result = Db::name('crm_order')->where('id', $id)->update($updateData);
        
        if ($result) {
            return $this->success('审核成功');
        }
        
        return $this->error('审核失败');
    }
    
    /**
     * 添加付款记录
     */
    public function addPayment()
    {
        $params = Request::param();
        $orderId = $params['order_id'];
        $userId = $this->getUserId();
        
        if (!$userId) {
            return $this->error('未登录或登录已过期', 401);
        }
        
        $order = Db::name('crm_order')->where('id', $orderId)->find();
        if (!$order) {
            return $this->error('订单不存在');
        }
        
        // 检查权限
        if ($order['signer_id'] != $userId) {
            // 获取用户信息判断权限
            $userInfo = Db::name('admin')
                ->field('id, group_id, did')
                ->where('id', $userId)
                ->find();
            
            if (!$userInfo || (isset($userInfo['group_id']) && $userInfo['group_id'] > 2)) {
                return $this->error('无权限操作');
            }
        }
        
        $data = [
            'order_id' => $orderId,
            'amount' => $params['amount'],
            'payment_time' => $params['payment_time'],
            'payment_method' => $params['payment_method'] ?? 1,
            'remark' => $params['remark'] ?? '',
            'voucher' => $params['voucher'] ?? '',
            'create_time' => date('Y-m-d H:i:s')
        ];
        
        $id = Db::name('crm_order_payment')->insertGetId($data);
        
        if ($id) {
            return $this->success('付款记录添加成功');
        }
        
        return $this->error('付款记录添加失败');
    }
    
    /**
     * 获取订单详情
     */
    public function detail()
    {
        $params = Request::param();
        $id = $params['id'];
        
        $order = Db::name('crm_order')
            ->alias('o')
            ->field('o.*, c.name as customer_name, u.name as user_name, d.title as dept_name')
            ->leftJoin('crm_customer c', 'o.customer_id = c.id')
            ->leftJoin('admin u', 'o.signer_id = u.id')
            ->leftJoin('department d', 'u.did = d.id')
            ->where('o.id', $id)
            ->where('o.delete_time', null)
            ->find();
            
        if (!$order) {
            return $this->error('订单不存在');
        }
        
        // 获取付款记录
        $payments = Db::name('crm_order_payment')
            ->where('order_id', $id)
            ->order('payment_time', 'desc')
            ->select();
            
        // 获取审核记录
        $reviews = Db::name('crm_order_review')
            ->alias('r')
            ->field('r.*, u.name as reviewer_name')
            ->leftJoin('admin u', 'r.reviewer_id = u.id')
            ->where('r.order_id', $id)
            ->order('r.create_time', 'desc')
            ->select();
            
        $order['payments'] = $payments;
        $order['reviews'] = $reviews;
        
        return $this->success($order, '获取成功');
    }
    
    /**
     * 生成订单编号
     */
    private function generateOrderNo()
    {
        $date = date('Ymd');
        $count = Db::name('crm_order')
            ->where('create_time', '>=', date('Y-m-d 00:00:00'))
            ->count();
            
        $serial = str_pad($count + 1, 4, '0', STR_PAD_LEFT);
        return "ORD{$date}{$serial}";
    }
    
    /**
     * 获取所有订单选项（类型、状态等）
     */
    public function options()
    {
        $options = [
            'orderTypes' => [
                ['value' => 1, 'label' => '诉讼业务'],
                ['value' => 2, 'label' => '非诉业务'],
                ['value' => 3, 'label' => '法律顾问'],
                ['value' => 4, 'label' => '其他业务']
            ],
            'statusOptions' => [
                ['value' => 1, 'label' => '待审核'],
                ['value' => 2, 'label' => '审核中'],
                ['value' => 3, 'label' => '执行中'],
                ['value' => 4, 'label' => '已完成'],
                ['value' => 5, 'label' => '已关闭']
            ],
            'paymentMethods' => [
                ['value' => 1, 'label' => '银行转账'],
                ['value' => 2, 'label' => '现金'],
                ['value' => 3, 'label' => '支付宝'],
                ['value' => 4, 'label' => '微信支付'],
                ['value' => 5, 'label' => '其他']
            ]
        ];
        
        return $this->success($options, '获取成功');
    }
    
    /**
     * 获取订单类型选项
     */
    public function typeOptions()
    {
        $options = [
            ['value' => 1, 'label' => '诉讼业务'],
            ['value' => 2, 'label' => '非诉业务'],
            ['value' => 3, 'label' => '法律顾问'],
            ['value' => 4, 'label' => '其他业务']
        ];
        
        return $this->success($options, '获取成功');
    }
    
    /**
     * 获取付款方式选项
     */
    public function paymentMethodOptions()
    {
        $options = [
            ['value' => 1, 'label' => '银行转账'],
            ['value' => 2, 'label' => '现金'],
            ['value' => 3, 'label' => '支付宝'],
            ['value' => 4, 'label' => '微信支付'],
            ['value' => 5, 'label' => '其他']
        ];
        
        return $this->success($options, '获取成功');
    }
    
    /**
     * 获取订单状态选项
     */
    public function statusOptions()
    {
        $options = [
            ['value' => 1, 'label' => '待审核'],
            ['value' => 2, 'label' => '审核中'],
            ['value' => 3, 'label' => '执行中'],
            ['value' => 4, 'label' => '已完成'],
            ['value' => 5, 'label' => '已关闭']
        ];
        
        return $this->success($options, '获取成功');
    }
    
    /**
     * 获取订单类型列表
     */
    public function getOrderTypeList()
    {
        $params = Request::param();
        $category = $params['category'] ?? null;
        $status = $params['status'] ?? null;
        
        $query = Db::name('crm_order_type')->where('status', 1);
        
        if ($category !== null) {
            $query->where('category', $category);
        }
        
        if ($status !== null) {
            $query->where('status', $status);
        }
        
        $list = $query->order('sort_order', 'asc')->select();
        
        return $this->success($list ? $list->toArray() : [], '获取成功');
    }
    
    /**
     * 根据订单大类获取类型
     */
    public function getOrderTypesByCategory($category)
    {
        $list = Db::name('crm_order_type')
            ->where('category', $category)
            ->where('status', 1)
            ->order('sort_order', 'asc')
            ->select();

        return $this->success($list ? $list->toArray() : [], '获取成功');
    }
    
    /**
     * 上传合同文件
     * @param array $files 文件数组
     * @return array 上传结果
     */
    private function uploadContractFiles($files)
    {
        try {
            // 确保是数组
            if (!is_array($files)) {
                $files = [$files];
            }
            
            $uploadedFiles = [];
            
            foreach ($files as $file) {
                // 验证文件类型和大小
                $validate = [
                    'size' => 50 * 1024 * 1024, // 50MB
                    'ext' => 'pdf,doc,docx,xls,xlsx,ppt,pptx,jpg,jpeg,png,gif'
                ];
                
                // 上传文件到 'contract' 磁盘
                $savename = Filesystem::disk('public')->putFile('contracts', $file, $validate);
                
                // 获取文件信息
                $fileInfo = [
                    'name' => $file->getOriginalName(),
                    'size' => $file->getSize(),
                    'type' => $file->getOriginalMime(),
                    'path' => $savename,
                    'url' => '/storage/' . $savename
                ];
                
                $uploadedFiles[] = $fileInfo;
            }
            
            return [
                'code' => 0,
                'msg' => '文件上传成功',
                'data' => $uploadedFiles
            ];
        } catch (ValidateException $e) {
            return [
                'code' => 1,
                'msg' => $e->getMessage(),
                'data' => []
            ];
        } catch (\Exception $e) {
            return [
                'code' => 1,
                'msg' => '文件上传失败：' . $e->getMessage(),
                'data' => []
            ];
        }
    }
}